<template>
  <div class="notice">
    <el-button icon="el-icon-close"
               @click="closeWindow"
               type="text"
               style="z-index: 100;position: absolute;top: 60px;right: 40px;font-size: 24px;color: #999">
    </el-button>
    <!--    :permission="permissionList"-->
    <!--    :before-open="beforeOpen"-->
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :search.sync="search"
               v-model="form"
               ref="crud"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   plain
                   @click="handleAdd">新增模版
        </el-button>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   @click="handleDelete()">删除模版
        </el-button>
      </template>
      <template slot="menuRight" slot-scope="{size}">
        <el-button round size="mini" style="width: 200px" @click="handleGlobal()">全局通知设置</el-button>
        <el-button round size="mini" style="width: 200px" @click="qiYeWeiXIn = true">企业微信管理</el-button>
        <el-button round size="mini" style="width: 200px" @click="feiShu = true">飞书设置</el-button>
      </template>
      <template slot-scope="{type,size,row}" slot="menu">
        <el-button icon="el-icon-view" :size="size" :type="type" @click="checkRow(row)"></el-button>
        <el-button icon="el-icon-edit " :size="size" :type="type" @click="editRow(row)"></el-button>
        <el-button icon="el-icon-delete" :size="size" :type="type" @click="handleDelete(row)"></el-button>
      </template>
    </avue-crud>
    <!-- 企业微信群管理弹窗 -->
    <div v-if="qiYeWeiXIn">
      <el-dialog
        title="企业微信-全局配置"
        :visible.sync="qiYeWeiXIn"
        :append-to-body="true"
        :before-close="handleClose">
        <el-row :gutter="20" style="width: 80%;margin: 0 auto;">
          <el-col span="8">通知群名称</el-col>
          <el-col span="8">webhook地址</el-col>
        </el-row>
        <el-form :model="item" ref="wxForm" :rules="wxRules" style="display: flex;"
                 v-for="(item,index) in qiYeWeiXInList" :key="index">
          <el-form-item prop="name" :rules="{ required: true, message: '请输入通知群名称', trigger: 'change' }">
            <el-input size="mini" class="offer-test" v-model="item.name"></el-input>
          </el-form-item>
          <el-form-item prop="address" :rules="{ required: true, message: '请输入webhook地址', trigger: 'change' }">
            <el-input size="mini" class="offer-status-alter" v-model="item.address"></el-input>
          </el-form-item>
          <el-row>
            <el-col span="8" style="display: flex;align-items: center">
              <el-button round size="small" class="offer-demo" @click="saveWeiXinGroup(item,index)">验证并保存</el-button>
              <div style="margin-left: 20px" @click="deleteItem(index,item.id)">
                <i style="font-size: 17px" class="el-icon-delete"></i>
              </div>
            </el-col>
          </el-row>
        </el-form>
        <el-row style="width: 80%; margin: 0 auto;padding-left: 11px">
          <el-button size="mini" type="primary" icon="el-icon-plus" @click="addWeixinNotice">添加通知群</el-button>
        </el-row>
      </el-dialog>
    </div>


    <!-- 飞书群管理弹窗 -->
    <el-drawer
      title="飞书设置"
      size="50%"
      :visible.sync="feiShu"
      :append-to-body="true">
      <div style="margin-bottom: 30px; display: flex; justify-content: center; align-items: center">
        <el-radio-group size="mini" v-model="feishuConfig.currentTab" @tabClick="changeFeishuConfigTab">
          <el-radio-button label="1">机器人应用</el-radio-button>
          <el-radio-button label="2">绑定用户</el-radio-button>
        </el-radio-group>
      </div>

      <el-form v-show="feishuConfig.currentTab === '1'" ref="feishuForm" :model="feishuForm" :rules="rules"
               label-width="150px" size="mini">
        <div style="width: 90%;margin: 0 auto;">
          <el-form-item label="飞书App ID" prop="appId">
            <el-input v-model="feishuForm.appId"></el-input>
          </el-form-item>
          <el-form-item label="飞书App Secret" prop="appSecret">
            <el-input show-password auto-complete="new-password"
                      v-model="feishuForm.appSecret"></el-input>
          </el-form-item>

          <div style="margin-top: 50px; display: flex;justify-content: center">
            <el-button size="mini" type="primary" @click="saveFeiShuCong">验证并保存</el-button>
            <el-button size="mini" type="primary" @click="saveFeiShuGroupMethod">获取最新飞书群列表</el-button>
            <el-button size="mini" @click="feiShu = false">取消</el-button>
          </div>

        </div>

      </el-form>

      <feishu-config v-show="feishuConfig.currentTab === '2'" @submit="feiShu = false" @close="feiShu = false" style="width: 90%;margin: 0 auto;">

      </feishu-config>
    </el-drawer>

    <el-drawer
      :title="label"
      size="40%"
      :visible.sync="dialogVisible"
      :before-close="closeDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :wrapperClosable="false"
      :append-to-body="true">
      <notice-edit :configValue="addForm" :showBase="true" :showOffer="true" :editable="!addCheck" @submit="submit" @close="closeDialog">
      </notice-edit>
    </el-drawer>

    <el-drawer
      title="全局通知设置"
      size="40%"
      :visible.sync="notifyConf"
      :before-close="closeGlobalDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :wrapperClosable="false"
      :append-to-body="true">
      <notice-edit :configValue="globalConfiguration" :showBase="false" :editable="true" @submit="submitGlobalConfig" @close="notifyConf = false">
      </notice-edit>
    </el-drawer>

  </div>
</template>

<script>
import {
  deleteTemplate,
  fieShuConf, getPage, globalConfAlter,
  saveFeiShuGroup, saveTemplateConf,
  selectInformGroup,
  getTemplate, getFeiShuApp, getGlobalConf, informGroup, getWeiXinGroup, dleWeiXinGroup,
} from "@/api/business/thirdpartyconf";
import {getList} from "@/api/system/role";
import func from '@/util/func'
import store from "@/store";
import {upOfferNoticeConf} from "@/api/business/thirdpartyconf";
import NoticeEdit from "@/views/system/notice/noticeEdit";
import FeishuConfig from "@/views/system/notice/feishuConfig";

export default {
  name: "noticeConfig",
  components: {
    NoticeEdit,
    FeishuConfig
  },
  data() {
    return {
      msg: '测试',
      notifyConf: false,

      feishuConfig: {
        currentTab: '1',
      },

      rules: {
        appId: [{required: true, message: "请输入app_id", trigger: 'change'}],
        appSecret: [{required: true, message: "请输入app_Secret", trigger: 'change'}]
      },
      wxRules: {
        name: [{required: true, message: "请输入群名称", trigger: 'change'}],
        address: [{required: true, message: "请输入机器人webhook地址", trigger: 'change'}]
      },
      feiShuGroup: [],
      feishuForm: {
        appId: '',
        appSecret: '',
        groupType: '0',
      },
      qiYeWeiXInList: [{
        name: '',
        address: '',
        groupType: 1,
      }],
      dialogVisible: false,
      label: '',
      qiYeWeiXIn: false,
      feiShu: false,
      loading: false,
      addCheck: false,//查看
      createdAudit: false,
      demand: false,
      data: [],
      search: {},
      form: {
        //模板名称
        //通知方式
      },
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        excelBtn: false,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        column: [
          {
            label: '序号',
            prop: 'id'
          },
          {
            label: '模板名称',
            prop: 'name',
            search: true,
          },
          {
            label: '通知方式',
            prop: 'notificeType',
            search: true,
            type: 'select',
            dicData: [
              {label: "飞书群", value: 0},
              {label: "企业微信群", value: 1},
              {label: "飞书个人", value: 2},
              // {label: "企业微信个人", value: 3},
            ]
          }
        ],
      },
      addForm: {
      },
      // addForm: {
      //   id: '',
      //   createStatusAlter: 100,
      //   offerEdit: 100,
      //   offerConflict: 100,
      //   requestCommunicate: 100,
      //   requestCreate: 100,
      //   assignTask: 100,
      //   uploadProduct: 100,
      //   productConfirm: 100,
      //   requestAdd: 100,
      //   creativeAudit: 100,
      //   auditSubmit: 100,
      //   auditResult: 100,
      //   requestContentAudit:100,
      //   requestEdit: 100,
      //   inProduction: 100,
      //   name: '',
      //   inProductionNoticeRoles: [],
      //   notificeType: [],
      //   createStatusAlterNoticeRoles: [],
      //   offerEditNoticeRoles: [],
      //   offerConflictNoticeRoles: [],
      //   requestCommunicateNoticeGroup: '',
      //   requestCreateNoticeRoles: [],
      //   assignTaskNoticeRoles: [],
      //   uploadProductNoticeRoles: [],
      //   productConfirmNoticeRoles: [],
      //   requestAddNoticeRoles: [],
      //   creativeAuditNoticeGroup: '',
      //   auditSubmitNoticeRoles: [],
      //   auditResultNoticeRoles: [],
      //   offerNoticeGroup: '',
      //   offerNotice:100,
      //   offerNoticeRoles: '',
      //   requestContentAuditNoticeRoles: [],
      //   requestEditNoticeRoles: []
      //
      // },
      // copy: {
      //   createStatusAlter: 100,
      //   offerEdit: 100,
      //   offerConflict: 100,
      //   requestCommunicate: 100,
      //   requestCreate: 100,
      //   assignTask: 100,
      //   uploadProduct: 100,
      //   productConfirm: 100,
      //   requestAdd: 100,
      //   creativeAudit: 100,
      //   auditSubmit: 100,
      //   auditResult: 100,
      //   requestContentAudit: 100,
      //   requestEdit: 100,
      //   inProduction: 100,
      //   name: '',
      //   inProductionNoticeRoles: [],
      //   notificeType: [],
      //   createStatusAlterNoticeRoles: [],
      //   offerEditNoticeRoles: [],
      //   offerConflictNoticeRoles: [],
      //   requestCommunicateNoticeGroup: '',
      //   requestCreateNoticeRoles: [],
      //   assignTaskNoticeRoles: [],
      //   uploadProductNoticeRoles: [],
      //   productConfirmNoticeRoles: [],
      //   requestAddNoticeRoles: [],
      //   creativeAuditNoticeGroup: '',
      //   auditSubmitNoticeRoles: [],
      //   auditResultNoticeRoles: [],
      //   offerNoticeGroup: '',
      //   offerNotice: 100,
      //   offerNoticeRoles: '',
      //   requestContentAuditNoticeRoles: [],
      //   requestEditNoticeRoles: []
      // },
      // testDome: 1,
      globalGroupList: [],
      globalConfiguration: {
        offerNotice: 0,
        offerNoticeRoles: [],
      },
      informGroupList: [],
      informRoleList: [],
      templateName: []
    }
  },
  created() {
    // if (store.getters.userInfo.is_agency === 1) {
    //   this.globalConfiguration.offerNoticeRoles = ['sales_manager', 'customer_manager']
    // }
    // if (store.getters.userInfo.is_agency === 0) {
    //   this.globalConfiguration.offerNoticeRoles = ['operator', 'admin']
    // }
    getList().then(res => {
      this.informRoleList = res.data.data.records
    })
    getFeiShuApp().then(res => {
      this.feishuForm.appId = res.data.data.appId
      this.feishuForm.appSecret = res.data.data.appSecret
    })
    /**
     * 获取全局配置
     */
    getGlobalConf().then(res => {
      //  TODO 这两行可以不要了
      // this.globalConfiguration.offerNoticeRoles = res.data.data.offerNoticeRoles.split(',')
      // this.globalConfiguration.offerNotice = res.data.data.offerNotice

      this.globalConfiguration = res.data.data;

    })
    getWeiXinGroup().then(res => {
      this.qiYeWeiXInList = res.data.data
    })
  },
  mounted() {
    this.$nextTick(() => {
      for (let i = 0; i < this.qiYeWeiXInList.length; i++) {
        if (this.$refs['wxForm'][i] != null) {
          this.$refs['wxForm'][i].clearValidate();
        }
      }
    });
    //获取初始化
  },
  methods: {
    handleClose(){
      this.qiYeWeiXIn = false
      this.qiYeWeiXInList.forEach((item,index) =>{
        if (item.name === "" && item.address === ""){
          this.qiYeWeiXInList.splice(index)
        }
      })
      console.log(this.qiYeWeiXInList)
    },
    sing() {
      this.page = {
        pageSize: 10,
        currentPage: 1,
        total: 0
      }
      this.refreshChange()
    },

    /*取消全局配置弹窗*/
    emptyGlobal() {
      this.notifyConf = false
      getGlobalConf().then(res => {
        this.globalConfiguration.offerNoticeRoles = res.data.data.offerNoticeRoles.split(',')
        this.globalConfiguration.offerNotice = res.data.data.offerNotice
      })
    },
    /*保存全局配置*/
    // openToClose() {
    //   let data = {
    //     offerNoticeRoles: this.globalConfiguration.offerNoticeRoles.join(','),
    //     offerNoticeGroup: this.globalConfiguration.offerNoticeGroup,
    //     offerNotice: this.globalConfiguration.offerNotice,
    //     notificeType: this.globalConfiguration.notificeType,
    //   }
    //   globalConfAlter(data).then(() => {
    //     this.$message({
    //       type: "success",
    //       message: "保存成功"
    //     })
    //     this.$emit("refresh")
    //   })
    //   this.notifyConf = false
    //   this.$bus.emit("parameterName", this.globalConfiguration.offerNotice)
    // },
    /*获取->选择通知方式群函数*/
    changeInformGroup(notificeType) {
      this.addForm.offerNoticeGroup = '';
      this.addForm.requestCommunicateNoticeGroup = '';
      this.addForm.creativeAuditNoticeGroup = '';
      this.getInformGroup(notificeType);
    },
    getInformGroup(parameter) {
      selectInformGroup(parameter).then(res => {
        this.informGroupList = res.data.data
      })
    },
    // /*全局配置获取->选择通知方式群函数*/
    // changeGlobalGroup(parameter,i) {
    //   if (i ===1){
    //     this.globalConfiguration.offerNoticeGroup = '';
    //   }
    //   this.getGlobalGroup(parameter);
    // },
    getGlobalGroup(parameter) {
      selectInformGroup(parameter).then(res => {
        this.globalGroupList = res.data.data
      })
    },
    /*新增弹窗->获取最新飞书群以及保存飞书群*/
    newSaveFeiSHuGroup() {
      if (this.feishuForm.appId !== "" && this.feishuForm.appSecret !== "") {
        saveFeiShuGroup(this.feishuForm).then(res => {
          if (res.data.data === "0") {
            this.changeInformGroup(this.addForm.notificeType)
            this.$message({
              type: "success",
              message: "已成功获取最新飞书群"
            })
          } else {
            this.$message({
              type: "warning",
              message: "获取最新飞书群失败,请检查app_id和appSecret是否正确"
            })
          }
        })
      } else {
        this.$message({
          type: "warning",
          message: "请输入app_id和app_secret"
        })
      }
    },
    /*获取最新飞书群以及保存飞书群*/
    saveFeiShuGroupMethod() {
      this.$refs['feishuForm'].validate((valid => {
        if (valid) {
          saveFeiShuGroup(this.feishuForm).then(res => {
            if (res.data.data === "0") {
              this.$message({
                type: "success",
                message: "已成功获取最新飞书群"
              })
            } else {
              this.$message({
                type: "warning",
                message: "获取最新飞书群失败,请检查app_id和appSecret是否正确"
              })
            }
            this.changeInformGroup(this.addForm.notificeType)
          })
        }
      }))
    },
    /*保存微信群名称和地址*/
    saveWeiXinGroup(item, index) {
      this.$refs['wxForm'][index].validate((valid => {
        console.log(valid)
        if (valid) {
          informGroup(item.name, item.address, item.groupType).then(() => {
            this.$message({
              type: "success",
              message: "操作成功"
            })
            getWeiXinGroup().then(res => {
              this.qiYeWeiXInList = res.data.data
            })
          })
        }
      }))
    },

    changeFeishuConfigTab(e) {
      console.log(e);
    },

    /*保存飞书配置*/
    saveFeiShuCong() {
      this.$refs['feishuForm'].validate((valid) => {
        if (valid) {
          let data = {
            appId: this.feishuForm.appId,
            appSecret: this.feishuForm.appSecret
          }
          fieShuConf(data).then(res => {

            if (res.data.data === "appId或者AppSecret不正确") {
              this.$message({
                type: "warning",
                message: "app_id或者app_secret不正确"
              })
              return
            }
            if (res.data.data === "保存成功") {
              this.$message({
                type: "success",
                message: "保存成功"
              })
              return
            }
            this.$message({
              type: "success",
              message: "更新成功"
            })
          })
        }
      })
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = false;
      getPage(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data
        this.page.total = data.total
        this.data = data.records;
        this.selectionClear();
      })
      // params.offerType = "admin,owner,manager,shared"
      // getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
      //   const data = res.data.data;
      //   this.page.total = data.total;
      //   this.data = data.records;
      //   this.loading = false;
      //   this.selectionClear();
      //   this.$nextTick(() => {
      //     this.$refs.crud.doLayout();
      //   });
      // });
    },
    handleGlobal() {
      getGlobalConf().then(res => {
        const global = res.data.data;
        global.id = null;
        Object.assign(this.globalConfiguration, global)
        this.notifyConf = true
      })

    },
    /**
     * 添加
     */
    handleAdd() {
      // 取全局数据
      getGlobalConf().then(res => {
        const global = res.data.data;
        global.id = null;
        global.offerIds = [];
        Object.assign(this.addForm, global)

        this.dialogVisible = true
        this.label = '新增通知模版'
      })
      // this.testDome = 0
    },
    /**
     * 删除通知方式
     */
    handleDelete(row) {
      let ids = '';
      if (row == null) {
        let idList = [];
        this.selectionList.forEach((row) => {
          idList.push(row.id);
        });
        ids = idList.join(',');
      } else {
        ids = row.id;
      }
      if (ids) {
        this.$confirm('删除通知配置模版, 是否继续?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
          // type: 'warning'
        }).then(() => {
          deleteTemplate(ids).then(() => {
            this.$message.success('通知配置模板删除成功');
            this.refreshChange();
          })
        });
      }

    },
    /**
     * 查看
     */
    checkRow(row) {
      this.editRow(row, false);
    },
    // /**
    //  * 编辑
    //  */
    editRow(row, edit = true) {
      getTemplate(row.id).then(res => {
        this.addForm = res.data.data;
        this.dialogVisible = true;
        this.addCheck = !edit;
        if (edit) {
          this.label = '编辑通知模版';
        } else {
          this.label = '查看通知模版';
        }
      });

    },

    /**
     * 保存模版修改
     * @param data
     */
    submit(data) {
      saveTemplateConf(data).then(res => {
        if (res.data.data === "yes" && this.label.includes('编辑')) {
          this.$confirm('通知配置保存成功,是否同步更新到已配置到当前模板的订单', '', {
            confirmButtonText: '更新',
            cancelButtonText: '不更新',
            type: 'warning'
          }).then(() => {
            this.syncTemplate(data)
          }).catch(() => {
            // this.$message({
            //   type: 'info',
            //   message: '已取消更新'
            // });
          });
        }

        if (this.label.includes('编辑') && res.data.data === "no") {
          this.$message({
            type: "success",
            message: "保存成功"
          })
        }
        if (this.label.includes('新增')) {
          this.$message({
            type: "success",
            message: "保存成功"
          })
        }

        this.closeDialog();
        this.refreshChange();

      });
    },

    syncTemplate(data) {
      upOfferNoticeConf(data).then(() => {
        this.$message({
          type: 'success',
          message: '同步模版更新成功!'
        });
      })
    },

    closeDialog() {
      this.dialogVisible = false;
      this.addCheck = false;
    },

    closeGlobalDialog() {
      this.notifyConf = false;
    },

    submitGlobalConfig(data) {
      globalConfAlter(data).then(() => {
        this.$message({
          type: "success",
          message: "保存成功"
        })
        this.closeGlobalDialog();
        this.$emit("refresh")
      })
    },

    addWeixinNotice() {
      this.qiYeWeiXInList.push({name: '', address: '', groupType: 1})
    },
    deleteItem(index, id) {
      if (id !== undefined) {
        this.$confirm('此操作将永久失效该数据, 是否继续?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
          // type: 'warning'
        }).then(() => {
          dleWeiXinGroup(id).then(() => {
            this.$message({
              type: "success",
              message: "删除成功"
            })
          })
          if (this.qiYeWeiXInList.length >= 1) {
            this.qiYeWeiXInList.splice(index, 1)
          }
        }).catch(() => {
          console.log('取消操作');
        });
      } else {
        if (this.qiYeWeiXInList.length > 1) {
          this.qiYeWeiXInList.splice(index, 1)
        }
      }
    },
    closeWindow() {
      this.$emit("close");
    }
  }
}
</script>

<style scoped lang="scss">
/deep/ .el-drawer__body {
  overflow-y: auto;
}

.notice {
  background: #fff;
  padding: 20px;
}

.form_item {
  padding-left: 10px;
}

.delete_icon {

}

.offer-status-alter {
  width: 200px;
  flex-direction: column;
  margin-left: 40px;
}

.offer-test {
  width: 200px;
  flex-direction: column;
  margin-left: 90px;
}

.offer-demo {
  margin-top: 5px;
  margin-left: 25px;
}
</style>
